package com.lzb.yabbs.app;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;

import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.gitonway.lee.niftynotification.lib.Effects;
import com.gitonway.lee.niftynotification.lib.NiftyNotificationView;
import com.lzb.yabbs.AppConfig;
import com.lzb.yabbs.R;
import com.lzb.yabbs.adapter.CardListAdapter;
import com.lzb.yabbs.dao.Card;
import com.lzb.yabbs.interfaces.GetCardsCallback;
import com.lzb.yabbs.net.GetCardsFromNet;
import com.melnykov.fab.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;

/**
 * Created by zaibinng on 2015/9/6.
 */
public class BaseListFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {

    private final String TAG=getClass().getSimpleName();
    private String url;
    private String title;
    private List<Card> mCards=new ArrayList<>();
    private final int GET_CARD_SUCCESS=0x123;
    private final int GET_CARD_FAIL=0x124;


    private ProgressBar mProgressBar;
    private ListView mCardListview;
    private FloatingActionButton fab;

    private CardListAdapter cardListAdapter;
    private SwipeRefreshLayout mSwipeRefreshLayout;




    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET_CARD_SUCCESS:
                    cardListAdapter.addCards(mCards);
                    mProgressBar.setVisibility(View.GONE);
                    fab.setVisibility(View.VISIBLE);
                    mSwipeRefreshLayout.setRefreshing(false);


                    break;
                case GET_CARD_FAIL:
                    NiftyNotificationView.build(getActivity(), "加载失败，请检查网络连接", Effects.flip, R.id.myfram)
                            .setIcon(R.mipmap.ic_launcher).show();
                    mProgressBar.setVisibility(View.GONE);
                    mSwipeRefreshLayout.setRefreshing(false);
                    break;

            }
        }
    };

    public BaseListFragment() {
        Log.d("BaseListFragment","BaseListFragment consturtor  ");

    }

    public static BaseListFragment newInstance(String url,String title){
        Log.d("BaseListFragment","newInstance  url:"+url);
        BaseListFragment baseListFragment=new BaseListFragment();
        Bundle args=new Bundle();
        args.putString("url",url);
        args.putString("title",title);
        baseListFragment.setArguments(args);
        return baseListFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d("BaseListFragment","onCreateView  ");
        return inflater.inflate(R.layout.base_list_fragment_layout,container,false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        Log.d("BaseListFragment", "onViewCreated  title:" + title);
        super.onViewCreated(view, savedInstanceState);
        mProgressBar= (ProgressBar) view.findViewById(R.id.progressbar);
        mCardListview= (ListView) view.findViewById(R.id.card_listview);
        mSwipeRefreshLayout= (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorScheme(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        cardListAdapter=new CardListAdapter(mCards,getActivity());
        mCardListview.setAdapter(cardListAdapter);

        mCardListview.setOnItemClickListener(this);
        fab = (FloatingActionButton) view.findViewById(R.id.fab);
        fab.attachToListView(mCardListview);
        fab.setOnClickListener(this);

        if(mCards.size()>0)
            fab.setVisibility(View.VISIBLE);
        mCardListview.refreshDrawableState();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d("BaseListFragment","onCreate  title:"+title);
        super.onCreate(savedInstanceState);

        if(getArguments()!=null){
            url=getArguments().getString("url");
            title=getArguments().getString("title");
        }
        if("".equals(url)){
            return;
        }
        initDatas();
    }

    private void initDatas(){
        GetCardsFromNet.getCards(AppConfig.URL_GET_LATEST, new GetCardsCallback() {
            @Override
            public void getCardsSuccess(List<Card> cards) {
                Log.d(TAG, "Cards size:" + cards.size());
                if(cards.size()>0) {
                    mCards = cards;
                    handler.sendEmptyMessage(GET_CARD_SUCCESS);
                }
            }

            @Override
            public void getCardFail(int reason) {
                Log.d(TAG, "getCardFail");
                handler.sendEmptyMessage(GET_CARD_FAIL);

            }
        },null);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent=new Intent(getActivity(),CardInfoActivity.class);
        intent.putExtra("card",mCards.get(position));
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        Log.d("BaseListFragment","onDestroy  title:"+title);
        super.onDestroy();
    }

    @Override
    public void onPause() {
        Log.d("BaseListFragment","onPause  title:"+title);
        super.onPause();
    }

    @Override
    public void onStart() {
        Log.d("BaseListFragment","onStart  title:"+title);
        super.onStart();
    }

    @Override
    public void onResume() {
        Log.d("BaseListFragment","onResume  title:"+title);

        super.onResume();
        if(mCards.size()>0){
            mProgressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        if(R.id.fab==v.getId()){
            startActivity(new Intent(getActivity(),SendCardActivity.class));
        }
    }

    @Override
    public void onRefresh() {
        initDatas();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==AppConfig.SEND_CARD_SUCESS_BACK_CODE){
            initDatas();
        }
    }
}
